package com.qz.center.file.server.common;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author gbx
 */
public class FileUtils {
    public static String saveFile(MultipartFile file) {
        String headUrl = null;
        String filePath = ConstantUtils.UPLOAD_PATH;

        String uuid = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        String suffix = "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        uuid += suffix;
        headUrl = ConstantUtils.LOCAL_HOST_ADDR + ConstantUtils.UPLOAD_MAPPING_PATH + "/" + uuid;
        System.out.println("headUrl:" + headUrl);
        String fileLocation = filePath + "/" + uuid;
        System.out.println("filePath:" + fileLocation);
        File imgFile = new File(fileLocation);

        if (!imgFile.getParentFile().exists()) {
            imgFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(imgFile);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return headUrl;
    }
}
